import XLSX from 'xlsx'
import FileSaver from "file-saver";
export function parseExcel(filename, fun) {
    let reader = new FileReader();
    reader.onload = function (ev) {
        const data = ev.target.result
        const workbook = XLSX.read(data, {
            type: 'binary',
        })
        fun ? fun(workbook) : ''

    };
    reader.readAsBinaryString(filename);
}

export function handleExcel(filename, handleRowsFun) {
    parseExcel(filename, (workbook) => {
        let dataGroup = []
        let i = 0
        for (let sheet in workbook.Sheets) {
            const boxSheet = workbook.Sheets[sheet]
            if (boxSheet) {
                let datas = XLSX.utils.sheet_to_json(boxSheet)
                //console.log(datas)
                dataGroup[i++] = datas
            }
        }
        handleRowsFun(dataGroup)
    })
}

function exportFromJson(filename,mapName) {
    let ws = XLSX.utils.json_to_sheet(data)
    // 创建workbook对象
    let wb = XLSX.utils.book_new()
    // 添加worksheet 到 workbook
    XLSX.utils.book_append_sheet(wb, ws, filename)
    // 写出 arraybuffer 数据
    let wb_out = XLSX.write(wb, { bookType: 'xlsx', type: 'array' })
    // 构建Blob对象
    const range = wb['!ref']
    if (range) {
        let pairs = range.split(":")
        let endColumn = 'A'
        let endIndex = 0
        if (pairs.length == 2) {
            endColumn = pairs[1].charAt(0)
            endIndex = parseInt(pairs[1].substring(1))
        }
        if(mapName){
            for (let c = 'A'; c <= endColumn; c++) {
                wb[c+ '1'].v = mapName[wb[c+ '1'].v]
             }
        }
    }
    let _blob = new Blob([wb_out], { type: 'application/octet-stream' })
    FileSaver(_blob, filename + ".xlsx")

}

export default {
    exportFromJson,
    handleExcel,
}